<template>
  <a-spin :spinning="spinning">
    <page-header-wrapper
      v-if="submitSuccess && submitErr"
      :tabList="tabList"
      :tab-active-key="activeKey"
      :tab-change="handleTabChange"
    >
      <template v-slot:extra>
        <a-button type="primary" shape="round" @click="handleSubmit">{{ isAdd ? '点击申报' : '确认修改' }}</a-button>
        <a-button type shape="round" @click="handleReset">{{ isAdd ? '清空重新填写' : '取消修改' }}</a-button>
      </template>
      <div v-if="!spinning">
        <info v-show="activeKey === 'info'" ref="info" :data="editData" />
        <report v-show="activeKey === 'report'" ref="report" :data="editData" />
      </div>
    </page-header-wrapper>
    <transition enter-active-class="zoom_in">
      <a-card :bordered="false" v-if="!submitSuccess">
        <a-result
          status="success"
          :title="$isEmpty($route.params.id) ? '提交成功' : '修改成功'"
          :sub-title="`申请${$isEmpty($route.params.id) ? '已提交' : '已修改'}，将于5个工作日内审核。`"
        >
          <template #extra>
            <y-button @click="handleClick('refresh')" v-if="$isEmpty($route.params.id)">继续填写</y-button>
            <y-button type="success" @click="handleClick('close')">关闭当前页面</y-button>
          </template>
        </a-result>
      </a-card>
    </transition>
    <transition enter-active-class="zoom_in">
      <a-card :bordered="false" v-if="!submitErr">
        <a-result status="error" title="提交失败">
          <template #extra>
            <y-button @click="handleClick('refresh')" v-if="$isEmpty($route.params.id)">继续填写</y-button>
            <y-button type="error" @click="handleClick('close')">关闭当前页面</y-button>
          </template>
        </a-result>
      </a-card>
    </transition>
  </a-spin>
</template>

<script>
import info from './infoCommunity.vue'
import report from './report.vue'
import { postApplication, getHousesCount } from '@/api/communityReviewManagement'
import { getNewProposerbyID, getSubsistenceAllowance } from '@/api/common'
import cloneDeep from 'lodash.clonedeep'
export default {
  name: 'applicationForm',
  components: {
    report,
    info,
  },
  created() {
    this.isAdd = this.$isEmpty(this.$route.params.id)
    if (!this.isAdd) {
      this.fetchData()
    }
  },
  data() {
    return {
      isAdd: true,
      tabList: [
        { key: 'info', tab: '保障用户基本信息' },
        { key: 'report', tab: '调查报告' },
      ],
      activeKey: 'info',
      submitSuccess: true,
      submitErr: true,
      spinning: false,
      editData: {},
    }
  },
  methods: {
    fetchData() {
      this.spinning = true
      getNewProposerbyID({
        ProposerID: this.$route.params.id,
      })
        .then((res) => {
          res.RegionNo = Number(res.RegionNo)
          res.TownshipNo = Number(res.TownshipNo)
          this.editData = res
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleTabChange(key) {
      this.activeKey = key
    },
    handleClick(type) {
      if (type === 'close') {
        this.$multiTab.closeCurrentPage()
      } else {
        this.$multiTab.refresh()
      }
    },
    handleSubmit(e) {
      const infoSumbit = this.$refs.info.handleSubmit()
      const reportSumbit = this.$refs.report.handleSubmit()
      Promise.all([infoSumbit, reportSumbit])
        .then((res) => {
          const data = cloneDeep({
            ...res[0],
            ...res[1],
            ApplyNO: this.editData.ApplyNO || '',
            ID: this.editData.ID || '',
            LastAlterUserID: this.$store.getters.userid,
            Builder: this.$store.getters.userid,
            proposerdelete: this.editData.proposerdelete || '',
          })
          if ((data.ApplyClass === '低保' || data.ApplyClass === '低收入') && data.CityVfyAreaPer > 15) {
            this.$message.error('当前核定人均面积大于15㎡，请修改后重新提交!')
            return
          }
          this.$loading.show({
            tip: '正在查询房屋套数是否满足条件，请稍后...',
          })
          const { HousCategory, proposerdetailhouses, proposerdetail } = data
          const idCard = proposerdetail.find((e) => Number(e.Relation) === 0).IDCards
          getHousesCount({
            idcards: idCard,
            count: HousCategory === '承租公房' || HousCategory === '自有产权房' ? proposerdetailhouses.length || 0 : 0,
          })
            .then((resHouse) => {
              const state = resHouse[0].state
              if (state === '1') {
                if (data.ApplyClass === '低保' && data.ClassName == 570) {
                  getSubsistenceAllowance({
                    idcards: idCard,
                  }).then((res) => {
                    if (res[0].state !== '1') {
                      this.$message.error('当前不存在低保成员，请检查后重新提交')
                    } else {
                      this.postData(data)
                    }
                  })
                } else {
                  this.postData(data)
                }
              }
            })
            .finally(() => {
              this.$loading.hide()
            })
        })
        .catch((err) => {
          this.$message.error({
            text: err,
          })
        })
    },
    postData(data) {
      this.$confirm({
        title: '提示',
        content: '确定申报吗？',
        onOk: () => {
          this.$loading.show({
            tip: '提交中，请稍后...',
          })
          data.proposerdetail.forEach((element) => {
            delete element.LiveDistrictAddressArr
            delete element.censusRegister
            if (['低保', '低收入'].includes(element.IfLowObjects)) {
              element.IfLowObjects = '有'
            } else {
              element.IfLowObjects = '无'
            }
            if (Array.isArray(element.GroupOfApplicants)) {
              element.GroupOfApplicants = element.GroupOfApplicants.join(',')
            }
          })
          postApplication({
            // ProposerModules: data,
            ProposerModules: Object.assign(data, {
              LastAlterUserID: this.$store.getters.userid,
            }),
            State: this.isAdd ? 'add' : 'update',
          })
            .then((res) => {
              if (res.code == 201) {
                this.submitErr = false
                this.$eventBus.$emit('primaryAuditRefresh')
              } else {
                this.submitSuccess = false
                this.$eventBus.$emit('primaryAuditRefresh')
              }
            })
            .finally(() => {
              this.$loading.hide()
            })
        },
        onCancel() {},
      })
    },
    handleReset() {
      if (this.isAdd) {
        if (this.activeKey === 'info') {
          this.$refs.info.handleReset()
        } else {
          this.$refs.report.handleReset()
        }
      } else {
        this.$multiTab.closeCurrentPage()
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .card-title {
  font-size: 20px;
  font-weight: bold;
}
</style>
